// Copyright (C) 2020 Focus Media Holding Ltd. All Rights Reserved.

package cn.pacerx.running.db.mybatis;

import java.util.regex.Pattern;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import com.google.common.base.Preconditions;

import lombok.experimental.UtilityClass;

/**
 * 注入到 mybatis ognl 上下文的静态方法
 *
 * @author gongshiwei@focusmedia.cn
 */
@UtilityClass
class MybatisOgnlUtils {
    private static final Pattern IDENTIFIER_REGEX = Pattern.compile("^[0-9a-zA-Z_]+$");

    /**
     * 检查SQL标识符 是否合法以防止 SQL 注入
     */
    @OgnlMethod({"column", "table"}) // 为了可读性, 取 "column", "table" 别名
    public static String checkIdentifier(String identifier) {
        Preconditions.checkArgument(StringUtils.isNoneBlank(identifier), "empty identifier");
        Preconditions.checkArgument(IDENTIFIER_REGEX.matcher(identifier).matches(), "bad identifier: %s", identifier);
        return identifier;
    }

    /**
     * 代理 {@linkplain ObjectUtils#isEmpty(Object)}.
     */
    @OgnlMethod("isEmpty")
    public static boolean isEmpty(Object obj) {
        return ObjectUtils.isEmpty(obj);
    }

    /**
     * 代理 {@linkplain ObjectUtils#isNotEmpty(Object)}.
     */
    @OgnlMethod("isNotEmpty")
    public static boolean isNotEmpty(Object obj) {
        return ObjectUtils.isNotEmpty(obj);
    }
}
